package com.clive.controller;

import com.clive.bean.DishesCategory;
import com.clive.service.DishesCategoryService;
import com.clive.service.DishesCategoryServiceImpl;
import com.clive.vo.DishResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "DishesCategoryController",urlPatterns = {"/dishesCategory"})
public class DishesCategoryController extends HttpServlet {
    private DishesCategoryService categoryService;
    private ObjectMapper mapper;
    @Override
    public void init() throws ServletException {
        categoryService = new DishesCategoryServiceImpl();
        mapper = new ObjectMapper();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        String op = request.getParameter("op");
//		查询所有菜品分类
        if("findAll".equals(op)){
            List<DishesCategory> list = categoryService.findDishesCategoryAll();
            DishResult result = DishResult.ok(list);
            String json = mapper.writeValueAsString(result);
            response.getWriter().print(json);

        }else if("addDishCategory".equals(op)){
            String dishCategoryName = request.getParameter("dishesCategoryName");
            DishesCategory dishesCategory = new DishesCategory();
            dishesCategory.setDishesCategoryName(dishCategoryName);
            boolean b = categoryService.addDishesCategory(dishesCategory);
            DishResult result = null;
            String json = null;
            if(b){
                result = DishResult.ok(null);
                json = mapper.writeValueAsString(result);
            }else{
                result = DishResult.error(null);
                json = mapper.writeValueAsString(result);
            }
            response.getWriter().print(json);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
